import { useWebSocket } from '@/compositions/notice/useWebSocket';
import { logout } from "@/api/login";
import { useDelCache } from "@/compositions/main/useDelCache";
import { queryAppList } from "@/api/orgPosition";
import { useUrlBreaker } from "@/compositions/main/useUrlBreaker";


export function useHeader(options: {loadTitle: boolean}) {
  const store = useStore()
  const router = useRouter()
  const {close} =useWebSocket()

  const { serviceType } = useUrlBreaker()
  const title = ref('')
  const username = store.state.user.username;
  const appList = ref([] as Array<any>);
  const _getTitle = async () => {
    const rs = await queryAppList({
      simple: true,
      includeMerchant: true,
    });
    if (rs.code == 200) {
      appList.value = rs.payload;
      title.value = nameFilter(serviceType);
    }

  }
  const nameFilter = (id: string) => {
    let name = "";
    if (!id) {
      id = store.state.user.currentService;
    }
    appList.value.forEach(i => {
      if (i.code == id) {
        name = i.name
      }
    })
    // switch (id) {
    //   case "MERCHANT":
    //     name = "商户系统";
    //     break;
    //   case "ACTIVITY":
    //     name = "营销活动管理";
    //     break;
    //   case "FLOW":
    //     name = "营销自动化";
    //     break;
    //   case "MALL":
    //     name = "商城管理";
    //     break;
    //   case "MATERIAL":
    //     name = "内容管理";
    //     break;
    //   case "MARKETING":
    //     name = "社区经理之家";
    //     break;
    //   case "AD":
    //     name = "智能广告";
    //     break;
    // }
    return name;
  };

  const exit = async () => {
    //关闭websocket
    await close()
    const rs = await logout();
    if (rs.code == 200) {
      ElMessage.success("退出登录成功");
    }
    useDelCache()
    const path = sessionStorage.getItem('loginPath') || '/login'
    router.push(path)
  };

  const goChangePassword = () => {
    router.push('/')
  }

  onBeforeMount(() => {
    if (options?.loadTitle) {
      _getTitle()
    }
  })

  return {
    title,
    username,
    exit,
  }
}
